package com.itheima.controller;

import com.itheima.exception.BusinessException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Controller
@RequestMapping("/upload")
public class UploadController {

    @RequestMapping("/file")
    public String upload(MultipartFile pic, HttpServletRequest request) throws IOException {
        //获取上传来的文件原始名
        String originalFilename = pic.getOriginalFilename();
        //获取该文件的扩展名
        String extensionName = originalFilename.substring(originalFilename.lastIndexOf("."));
        //对文件类型进行判断
        if (!extensionName.equals(".exe")){
            //生成一个唯一的文件名
            String filename = UUID.randomUUID().toString() + extensionName;
            //获取服务器中的upload文件的绝对路径
            String realPath = request.getServletContext().getRealPath("/upload");
            //将用户上传来的图片存储到服务器
            pic.transferTo(new File(realPath+File.separator+filename));
        }else {
            throw new BusinessException("文件类型不对哦~");
        }
        return "uploadsuccess.jsp";
    }
}
